import mysql from "mysql"
import { stringify } from "querystring";
export default class shopcar {
    static addshopcar(data, res) {
        var connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: 'root',
            port: '3306',
            database: 'test'
        });

        if (data.split('{')[0] !== '') data = data.match(/(\{.*?\})/)[1]
        data = JSON.parse(data)
        connection.connect();
        var addSql = 'INSERT INTO test.list(sku_id,price,name,ali_image,num) VALUES(' + '"' + data.sku_id + '"' + ',' + '"' + data.price + '"' + ',' + '"' + data.name + '"' + ',' + '"' + data.image + '"' + ',' + '"' + data.num + '"' + ')';
        res.writeHead(200, {
            "Content-Type": "application/json;charset=utf-8",
            "Access-Control-Allow-Origin": "*"
        })
        connection.query(addSql, function (err, result) {
            if (err) {
                console.log('[INSERT ERROR] - ', err.message);
                return;
            }
            return res.end(JSON.stringify(result));
        });

        connection.end();
    }
    static delshopcar(data, res) {
        var connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: 'root',
            port: '3306',
            database: 'test'
        });
        if (data.split('{')[0] !== '') data = data.match(/(\{.*?\})/)[1]
        data = JSON.parse(data)
        connection.connect();
        var delSql = 'DELETE FROM test.list where sku_id=' + data.sku_id;
        res.writeHead(200, {
            "Content-Type": "application/json;charset=utf-8",
            "Access-Control-Allow-Origin": "*"
        })
        connection.query(delSql, function (err, result) {
            if (err) {
                console.log('[INSERT ERROR] - ', err.message);
                return;
            }
            return res.end(JSON.stringify(result));
        });

        connection.end();
    }
    static changeshopcar(data) {
        var connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: 'root',
            port: '3306',
            database: 'test'
        });
        if (data.split('{')[0] !== '') data = data.match(/(\{.*?\})/)[1]
        data = JSON.parse(data)

        connection.connect();
        var modSql = "UPDATE test.list SET num=? WHERE sku_id=?";
        var modSqlParams = [data.num, data.sku_id];
        console.log(modSqlParams);
        connection.query(modSql, modSqlParams);

        connection.end();
    }
}